package com.barradata.app0624.modules.camera

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.example.hfiveandaplication.utils.FileUtils
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.PictureResult
import com.squareup.picasso.Picasso
import crossoverone.statuslib.StatusUtil
import kotlinx.android.synthetic.main.camera_idcard_activity.*
import top.zibin.luban.Luban
import java.io.File

/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/5 17:16
 **/
class CameraActivity : BaseActivity() {
    companion object {
        private const val TYPE_KEY = "TYPE_KEY"

        fun actionStart(context: Context, type: ApiService.UploadImageType) {
            val intent = Intent(context, CameraActivity::class.java)
            intent.putExtra(TYPE_KEY, type)
            context.startActivity(intent)
        }
    }

    private lateinit var type: ApiService.UploadImageType
    private lateinit var photoData: ByteArray
    private lateinit var photoFile: File

    override fun getLayoutId() = R.layout.camera_idcard_activity

    override fun initView() {
        setupStatusBar()
        setupMaskLayer()
        setupCameraView()
        setupCameraButtons()
        setupPhotoConfirmButtons()
    }

    private fun setupPhotoConfirmButtons() {
        confirm_button.clickV().subscribe {
            RxBus.post(CameraCallbackEvent(type, photoData, photoFile))
            finish()
        }.autoClean()
        cancel_button.clickV().subscribe {
            showCameraGroup()
            camera_view.open()
            confirm_photo_iv.setImageDrawable(null)
        }.autoClean()
    }

    private fun setupCameraButtons() {
        camera_capture_button.clickV().filter { !camera_view.isTakingPicture }.subscribe {
            camera_view.takePictureSnapshot()
        }.autoClean()
        camera_toggle_button.clickV().filter { !camera_view.isTakingPicture }.subscribe {
            camera_view.toggleFacing()
        }.autoClean()
    }

    private fun setupCameraView() {
        camera_view.setLifecycleOwner(this)
        camera_view.addCameraListener(object : CameraListener() {
            override fun onPictureTaken(result: PictureResult) {
                logD(result.data.size.toString())
                showConfirmGroup()
                camera_view.close() // 确认相片时关闭摄像头，节省性能开销
                photoData = result.data
                result.toBitmap {
                    confirm_photo_iv.setImageBitmap(it)
                }
                result.toFile(FileUtils.getPicPath()) {
                    logD(it?.path.orEmpty())
                    photoFile = Luban.with(this@CameraActivity).load(it).get().first()
//                    photoFile = it!!
                }
            }
        })
    }

    private fun setupMaskLayer() {
        type = intent.getSerializableExtra(TYPE_KEY) as ApiService.UploadImageType
        when (type) {
            ApiService.UploadImageType.ID_CARD -> {
                Picasso.get().load(R.drawable.camera_fg_idcard).fit().into(camera_mask_iv)
            }
            ApiService.UploadImageType.ID_CARD_WITH_PORTRAIT -> {
                Picasso.get().load(R.drawable.camera_fg_idcard_with_portrait).fit().into(camera_mask_iv)
            }
            else -> camera_mask_iv.setImageDrawable(null)
        }
    }

    private fun setupStatusBar() {
        StatusUtil.setUseStatusBarColor(this, Color.TRANSPARENT)
        StatusUtil.setSystemStatus(this, true, false)
    }

    private fun showCameraGroup() {
        camera_group.visibility = View.VISIBLE
        confirm_group.visibility = View.GONE
    }

    private fun showConfirmGroup() {
        camera_group.visibility = View.GONE
        confirm_group.visibility = View.VISIBLE
    }
}
